#include "ftlatlonedit.h"
#include "ftcontrols.h"
#include "configuration.h"

#include "ll-utm/LatLong-UTMconversion.h"

#include "controls/latlondialog.h"

FTLatLonEdit::FTLatLonEdit(double a, double o, Qt::Orientation x, QWidget* parent) :
    FTBasicWidget(parent)
{
    _edit = true;
    setOrientation( x );
    setLatLon( a, o );
    mouse_down = false;
    connect( configuration, SIGNAL(coordFormatChanged()),
             this, SLOT(formatChanged()) );
}

void FTLatLonEdit::formatChanged()
{
    makeText();
    // Get the new would-be size
    QSize new_size = minimumSizeHint();
    // Ignore any smaller sizes and keep the current one:
    if ( new_size.width() < width() )
        new_size.setWidth( width() );
    if ( new_size.height() < height() )
        new_size.setHeight( height() );
    // Resize to fit the new enlarged size (or keep the current size)
    resize( new_size );
}

void FTLatLonEdit::setOrientation(Qt::Orientation x)
{
    if ( x == Qt::Vertical )
    {
        _orientation = Qt::Vertical;
        setSizePolicy( QSizePolicy::Preferred, QSizePolicy::MinimumExpanding );
    }
    else if ( x == Qt::Horizontal )
    {
        _orientation = Qt::Horizontal;
        setSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::Preferred );
    }
    update();
}

void FTLatLonEdit::setLatLon(double a, double o)
{
    latlon.setLatitude( a );
    latlon.setLongitude( o );
    makeText();
    update();
}

double FTLatLonEdit::latitude() const
{
    return latlon.latitude();
}

double FTLatLonEdit::longitude() const
{
    return latlon.longitude();
}

void FTLatLonEdit::paintEvent(QPaintEvent * )
{
    QPalette palette = QApplication::palette();
    QPainter painter(this);
    palette.setCurrentColorGroup( FT_COLOR_GROUP );

    QPen pen = palette.color( mouse_down ? QPalette::HighlightedText :
                                           QPalette::WindowText );

    painter.setPen( pen );
    if ( _backgroundStyle != Qt::NoBrush )
    {
        QBrush brush = painter.brush();
        brush.setColor( palette.color( QPalette::Window ) );
        brush.setStyle( _backgroundStyle );
        painter.fillRect( rect(), brush );
    }
    QRect border = rect().adjusted(1,1,-1,-1);
    if ( mouse_down )
        painter.drawRect( border );

    // Draw the text
    painter.drawText( border, Qt::AlignCenter, calculatedString );

}

void FTLatLonEdit::makeText()
{
    QString str1 = tr("Latitude / Longitude: ") + QString('\n');
    QString str2;
    Configuration::coordinate_format cf = configuration->defaultCoordFormat();
    if ( cf == Configuration::decimal )
        str2 = latlon.toString( QGeoCoordinate::DegreesWithHemisphere );
    else if ( cf == Configuration::degrees_minutes_seconds )
        str2 = latlon.toString( QGeoCoordinate::DegreesMinutesSecondsWithHemisphere );
    else if ( cf == Configuration::degrees_minutes )
        str2 = latlon.toString( QGeoCoordinate::DegreesMinutesWithHemisphere );
    else if ( cf == Configuration::utm )
    {
        double utmN, utmE;
        char utmZc[20];
        LLtoUTM( 23, latlon.latitude(), latlon.longitude(), utmN, utmE, utmZc);
        int utmE_xxx = ((int)utmE) % 1000;
        int utmE_xxx_xxx = ((int)utmE) % 1000000;
        int utmN_xxx = ((int)utmN) % 1000;
        int utmN_xxx_xxx = ((int)utmN) % 1000000;
        str1 = QString("UTM %1\n").arg(utmZc);
        str2 = QString("%1 %2E %3 %4N").arg(utmE_xxx_xxx)
                                    .arg(utmE_xxx)
                                    .arg(utmN_xxx_xxx)
                                    .arg(utmN_xxx);
    }

    if ( str2 == "" )
        str2 = "xxx, xxx";
    if (_orientation == Qt::Vertical)
        str2 = str2.replace( ",", "\n" );
    calculatedString = str1 + str2;
}

void FTLatLonEdit::mousePressEvent(QMouseEvent *)
{
    if ( !_edit )
        return;
    mouse_down = true;
    update();
}

void FTLatLonEdit::mouseReleaseEvent(QMouseEvent *)
{
    if ( !_edit )
        return;

    if ( isEnabled() && mouse_down )
    {
        double lat, lon;
        LatLonDialog dialog( latlon.latitude(),
                             latlon.longitude(),
                             configuration->defaultCoordFormat() );
        if ( dialog.execLatLon( lat, lon ) )
        {
            setLatLon( lat, lon );
            emit updated( lat, lon );
        }
    }
    mouse_down = false;
    update();
}

QSize FTLatLonEdit::sizeHint() const
{
    int min_height = FTControls::defaultHeight();
    int padding = FTControls::defaultPadding();

    QFontMetrics fm(font());
    QSize size = fm.size( Qt::AlignCenter, calculatedString ) +
            QSize( padding*2,padding );

    if ( size.width() < min_height )
        size.setWidth( min_height );

    if ( size.height() < min_height )
        size.setHeight( min_height );
    return size;
}

QSize FTLatLonEdit::minimumSizeHint() const
{
    return sizeHint();
}

bool FTLatLonEdit::isEdit() const
{
    return _edit;
}

void FTLatLonEdit::setEdit(bool e)
{
    _edit = e;
}
